<template>
  <a-layout class="post-detail-layout">
    <a-layout-content class="content">
      <div class="post-detail-container">
        <!-- 返回按钮 -->
        <div class="back-btn">
          <a-button @click="goBack" icon="arrow-left">返回</a-button>
        </div>

        <h2 class="post-title">{{ post.title }}</h2>

        <!-- 在post-meta部分添加点赞收藏 -->
        <div class="post-meta">
          <span class="author">作者: {{ post.userName }}</span>
        </div>

        <!-- 删除帖子按钮，只有满足条件时显示 -->
        <div v-if="canDelete" class="delete-btn">
          <a-button type="danger" @click="deletePost">删除帖子</a-button>
        </div>

        <div class="post-content" v-html="post.content"></div>

        <!-- 评论部分 -->
        <div>
          <div class="comment-section">
            <h3>评论</h3>

            <!-- 评论列表 -->
            <div
              v-for="comment in comments"
              :key="comment.id"
              class="comment-item"
            >
              <div>
                <strong>{{ comment.userName }}</strong> 评论：
              </div>
              <p>{{ comment.content }}</p>
              <div class="comment-time">{{ comment.createTime }}</div>

              <!-- 删除评论按钮 -->
              <div v-if="canDeleteComment(comment)">
                <a-button type="danger" @click="deleteComment(comment.id)"
                  >删除评论</a-button
                >
              </div>
            </div>

            <!-- 评论输入框 -->
            <a-textarea
              v-model="newComment"
              rows="4"
              placeholder="写下你的评论..."
              style="margin-bottom: 20px"
            ></a-textarea>

            <!-- 提交评论按钮 -->
            <a-button type="primary" @click="submitComment">提交评论</a-button>
          </div>
        </div>
      </div>
    </a-layout-content>
  </a-layout>
</template>

<script>
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router"; // 引入 useRoute 和 useRouter
import request from "@/utils/request"; // 引入请求方法
import { useStore } from "vuex"; // 引入 useStore 来访问 Vuex
// 新增图标引入
import { LikeOutlined, StarOutlined } from "@ant-design/icons-vue";
import MarkdownIt from "markdown-it";
import { ElMessage } from "element-plus";
export default {
  name: "PostDetail",
  components: {
    LikeOutlined, // 注册图标组件
    StarOutlined, // 注册图标组件
  },
  setup() {
    const store = useStore(); // 使用 useStore 获取 Vuex store
    const route = useRoute(); // 获取当前路由
    const router = useRouter(); // 获取路由实例
    const postId = route.params.postId; // 获取动态路由参数 postId
    const post = ref({}); // 用来存储帖子内容
    const comments = ref([]); // 存储评论列表
    const newComment = ref(""); // 存储新评论的内容
    const md = new MarkdownIt({
      html: true, // 启用 HTML 解析
      linkify: true, // 自动链接
      typographer: true, // 启用语法
    }).use(require("markdown-it-prism")); // 可选：使用 prism.js 语法高亮

    // 使用 reactive 创建一个响应式对象
    const commentData = ref({
      title: postId,
      userName: "", // 从 Vuex 获取用户名
      userId: "", // 当前用户ID
      content: newComment.value,
    });

    // 判断是否可以删除帖子
    const canDelete = computed(() => {
      const currentUser = store.state.user && store.state.user.user;
      if (currentUser) {
        return (
          currentUser.id === post.value.userId || currentUser.permission === "1"
        );
      }
      return false;
    });

    // 判断是否可以删除评论
    const canDeleteComment = (comment) => {
      const currentUser = store.state.user && store.state.user.user;
      return (
        currentUser &&
        (currentUser.permission === "1" || // 管理员
          currentUser.id === post.value.userId || // 帖子作者
          currentUser.id === comment.userId) // 评论的作者
      );
    };

    // 删除评论
    const deleteComment = (commentId) => {
      const currentUser = store.state.user && store.state.user.user;
      if (!currentUser) {
        ElMessage.error("用户信息未加载，无法删除评论");
        return;
      }

      request
        .delete(`/forum/deleteComment/${commentId}`) // 删除评论接口
        .then((response) => {
          refreshPostData(); // 删除评论后刷新帖子数据
        })
        .catch((error) => {
          ElMessage.error("删除评论失败");
        });
    };

    // 根据 postId 获取帖子详情
    const refreshPostData = () => {
      request
        .get(`/forum/selectById?id=${postId}`) // 根据 postId 获取帖子详情
        .then((response) => {
          comments.value = response.data2; // 获取评论数据
          post.value = response.data; // 获取数据后存储在 post 中

          // 将 Markdown 内容转换为 HTML
          post.value.content = md.render(post.value.content); // 使用 MarkdownIt 转换 Markdown 为 HTML
        })
        .catch((error) => {
          console.error("获取帖子详情失败");
        });
    };

    // 根据 postId 获取帖子详情
    onMounted(() => {
      // 确保 store 已经正确加载并且包含用户数据
      if (store.state.user && store.state.user.user) {
        commentData.value.userName = store.state.user.user.username; // 从 Vuex 获取用户名
        commentData.value.userId = store.state.user.user.id; // 从 Vuex 获取用户ID
      } else {
        console.error("用户信息未加载");
      }
      request
        .get(`/forum/selectById?id=${postId}`) // 根据 postId 获取帖子详情
        .then((response) => {
          comments.value = response.data2; // 获取评论数据
          post.value = response.data; // 获取数据后存储在 post 中
        })
        .catch((error) => {
          console.error("获取帖子详情失败");
        });
    });

    // 返回上一页的函数
    const goBack = () => {
      router.push("/forum"); // 返回论坛首页或指定页面
    };

    // 提交评论
    const submitComment = () => {
      if (!newComment.value) {
        ElMessage.error("评论内容不能为空");
        return;
      }
      commentData.value.content = newComment.value;
      request
        .post("/forum/addcomment", commentData.value) // 提交评论接口
        .then((response) => {
          refreshPostData();
          newComment.value = "";
        })
        .catch((error) => {
          ElMessage.error("评论失败");
        });
    };

    // 删除帖子
    const deletePost = () => {
      const currentUser = store.state.user && store.state.user.user;
      if (!currentUser) {
        ElMessage.error("用户信息未加载，无法删除帖子");
        return;
      }

      request
        .delete(`/forum/delete/${postId}`)
        .then((response) => {
          ElMessage.success("帖子删除成功");
          router.push("/forum");
        })
        .catch((error) => {
          ElMessage.error("删除帖子失败");
        });
    };

    const handleLike = () => {
      request
        .put(`/forum/thumb/${postId}`)
        .then((response) => {
          refreshPostData();
        })
        .catch((error) => {
          console.error("失败"); // 打印失败的错误信息
        });
    };

    const handleCollect = () => {
      request
        .put(`/forum/favour/${postId}`)
        .then((response) => {
          refreshPostData();
        })
        .catch((error) => {
          console.error("失败"); // 打印失败的错误信息
        });
    };

    return {
      post,
      comments,
      newComment,
      goBack,
      submitComment,
      canDelete,
      deletePost,
      handleLike,
      handleCollect,
      StarOutlined,
      canDeleteComment,
      deleteComment,
    };
  },
};
</script>

<style scoped>
.post-detail-layout {
  background-color: #f9f9f9;
  padding: 40px 0;
}

.post-detail-container {
  background: white;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-width: 1200px;
  margin: 0 auto;
  font-family: "Arial", sans-serif;
  position: relative;
}

.post-title {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.post-meta {
  font-size: 16px;
  color: #888;
  margin-bottom: 20px;
}

.author {
  font-style: italic;
}

.post-content {
  font-size: 18px;
  line-height: 1.6;
  color: #555;
}

.comment-section {
  margin-top: 40px;
}

.comment-item {
  background: #f9f9f9;
  padding: 10px;
  margin-bottom: 20px;
  border-radius: 8px;
}

.comment-time {
  font-size: 12px;
  color: #888;
  margin-top: 10px;
}

/* 返回按钮样式 */
.back-btn {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
}

.delete-btn {
  margin-top: 20px;
}

/* 新增样式 */
.action-buttons {
  margin-top: 8px;
  display: flex;
  align-items: center;
}

.action-btn {
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

/* 自定义按钮悬停效果 */
.action-btn .anticon {
  margin-right: 8px;
}
</style>
